/**
*
* @brief	Calendar
* @author	yun
* @date		2016-12-21
* @desc
* @version
*
*/

#include	"platform_calendar.h"

#include	"platform_logger.h"
#include	"stm32f2xx.h"


int platform_calendar_show(void){
    RTC_TimeTypeDef time;
	RTC_DateTypeDef date;
	RTC_GetTime(RTC_Format_BIN, &time);
	RTC_GetDate(RTC_Format_BIN, &date);
	log_info_printf("time: 20%02d-%02d-%02d %02d:%02d:%02d",
		date.RTC_Year, date.RTC_Month, date.RTC_Date,
		time.RTC_Hours, time.RTC_Minutes, time.RTC_Seconds);
	return 0;
}

//2016-12-29 14:53:26


#define 	RTC_ASYNCH_PREDIV  		0x7F   
#define 	RTC_SYNCH_PREDIV   		0x00FF 

int platform_calendar_init(void){
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
	PWR_BackupAccessCmd(ENABLE);

	RTC_EnterInitMode();
	RCC_LSEConfig(RCC_LSE_ON);
	while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET){}
		
	RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
	RCC_RTCCLKCmd(ENABLE);
	RTC_WaitForSynchro();
	
	RTC_InitTypeDef RTC_InitStructure;
	RTC_InitStructure.RTC_SynchPrediv = RTC_SYNCH_PREDIV;
	RTC_InitStructure.RTC_AsynchPrediv = RTC_ASYNCH_PREDIV;
	RTC_InitStructure.RTC_HourFormat = RTC_HourFormat_24;
	RTC_Init(&RTC_InitStructure);
	
	return 0;
}

int platform_calendar_set(char *time){
	int year, month, day, hour, minutes, seconds;
	if(sscanf(time, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minutes, &seconds) != 6){
		return -1;
	}

	RTC_DateTypeDef 	rtcDateStructure;
	rtcDateStructure.RTC_Year 	= 	year - 2000;
	rtcDateStructure.RTC_Month 	= 	month;
	rtcDateStructure.RTC_Date	= 	day;
	rtcDateStructure.RTC_WeekDay =   RTC_Weekday_Monday;

	RTC_TimeTypeDef 	rtcTimeStructure;
	rtcTimeStructure.RTC_Hours = hour;
	rtcTimeStructure.RTC_Minutes = minutes;
	rtcTimeStructure.RTC_Seconds = seconds;
	
	if(RTC_SetDate(RTC_Format_BIN, &rtcDateStructure) != SUCCESS){
		return -1;
	}		
	
	if(RTC_SetTime(RTC_Format_BIN, &rtcTimeStructure) != SUCCESS){
		return -1;
	}
	
	return 0;
}


int platform_calendar_get(char * buffer){
	RTC_TimeTypeDef time;
	RTC_DateTypeDef date;
	RTC_GetTime(RTC_Format_BIN, &time);
	RTC_GetDate(RTC_Format_BIN, &date);
	return sprintf(buffer, "20%02d-%02d-%02d %02d:%02d:%02d",
		date.RTC_Year, date.RTC_Month, date.RTC_Date,
		time.RTC_Hours, time.RTC_Minutes, time.RTC_Seconds);
}


int platform_calendar_test(void){
		return 0;
}

